var action = '';
var sessionTime = setTimeout("logout()", 910000); // 15mns+10secs
var keyPressCounter = 0;
   
function doSetup() {
  var username = $("#username").val();
  var password = $("#password").val();
  var secureAccess = $("#secureAccess").val();
  var currency = $("#currency").val();
  var language = $("#language").val();
  $("#setupSubmitButton").attr("disabled", "true");
  // show the loading div
  $('#loading').show();
  $.ajax({
    type: "POST",
    url: "index.php",
    data: "ajax=1&action=setupSubmit&username="+username+"&password="+password+"&secureAccess="+secureAccess+"&language="+language+"&currency="+currency,
    cache: false,
    dataType: 'json',
    timeout: 5000,
    success: function(data, status){
      $('#loading').hide();
      if(data.error != 0) {
        $('#loading').hide();
        $("#setupSubmitButton").removeAttr("disabled");
        alert(data.msg);
        }
      else {
        alert(data.msg);
        location.reload();
        }
      },
    error: function (data, status, e) {
			$('#loading').hide();
      $("#setupSubmitButton").removeAttr("disabled");
      alert("Error: "+status+" ("+e+")");
			}
    });
  return false;
  }
  
function wizard(id) {
  switch(id) {
    case 1:
      $('#wizard').load('index.php', {'ajax':1, 'action': 'editCategories'},function(){  });
      $('#step1').attr({src: "style/icons/transmit_go.png"});
      $('#step2,#step3,#step4').attr({src: "style/icons/transmit.png"});
      
    break;
    case 2:
      $('#wizard').load('index.php', {'ajax':1, 'toDiv': 'wizard', 'action':'addTransactionsWizard'},function(){
        $('#subAction1').load('index.php', {'ajax':1, 'toDiv': 'subAction1', 'action':'addTransactionsManualy'},function(){  });
      });
      $('#step2').attr({src: "style/icons/transmit_go.png"});
      $('#step1,#step3,#step4').attr({src: "style/icons/transmit.png"});
      $('#step2button').removeAttr("disabled"); 
    break;
    case 3:
      $('#wizard').load('index.php', {'ajax':1, 'action': 'editKeywords'},function(){  });
      $('#step3').attr({src: "style/icons/transmit_go.png"});
      $('#step1,#step2,#step4').attr({src: "style/icons/transmit.png"});
    break;
    case 4:
      $('#wizard').load('index.php', {'ajax':1, 'action': 'autoFileItem'},function(){  });
      $('#step4').attr({src: "style/icons/transmit_go.png"});
      $('#step1,#step2,#step3').attr({src: "style/icons/transmit.png"});
    break;
    default:
      $('#wizard').load('index.php', {'ajax':1, 'action': 'editCategories'},function(){  });
    break;
    }
  return false;
  }

function enableWizardStep(id) {
  switch(id) {
    case 2:
      $('#step2button').removeAttr("disabled"); 
    break;
    case 3:
      $('#step3button').removeAttr("disabled");
    break;
    case 4:
      $('#step4button').removeAttr("disabled");
    break;
    }
  return false;
  }
  
// perform a search based on a keyword
function searchFormSubmit() {
    resetLogout();
    searchKey = $("#keys").val();
    if(searchKey.length < 3) return;
    $("#loading").show();
    $('#searchIcon').attr({src: "style/icons/hourglass.png"});
    keyPressCounter++;
    $.ajax({
      type: "POST",
      timeout: 15000,
      url: "index.php",
      data: "ajax=1&action=search_keyWord="+searchKey,
      cache: false,
      success: function(html){
        $("#main").empty();
        $("#main").prepend(html);
        $("#main").show();
        keyPressCounter--;
        if(keyPressCounter == 0) {
          $("#loading").hide();
          $('#searchIcon').attr({src: "style/icons/zoom.png"});
          }
        }
      });
    return false;
    }

// perform a file upload to the server
function ajaxFileUpload()	{
    resetLogout();
    // show the loading on start
		$("#loading").ajaxStart(function(){
			$(this).show();
		});
		// hide the report div on start
		$('#importDetails').ajaxStart(function(){
    		$(this).hide();
		});
		// hide the loading on complete
		$("#loading").ajaxComplete(function(){
    		$(this).hide();
		});
		// hide any errors
    $("#qifUploadError").ajaxStart(function(){
			$(this).hide();
		});
		// show the loading file div on start
    $("#qifUploadLoading").ajaxStart(function(){
			$(this).show();
		});
	  // hide the upload button on start
		$("#jqUploader").ajaxStart(function(){
			$(this).hide();
		});
		// hide the result div on start
    $("#qifUploadResultCount").ajaxStart(function(){
			$(this).hide();
		});
		// hide the error div on start
		$("#qifUploadError").ajaxStart(function(){
      $(this).hide();
    });
		action = $("#action").val();
		dateLocale = $("input[name=QIFLocaleType]:checked:checked").val(); 
		$.ajaxFileUpload ({
				url:'index.php?action='+action+'_QIFLocaleType='+dateLocale+'_ajax=1',
				secureuri:false,
				fileElementId:'fileToUpload',
				dataType: 'json',
				success: function (data, status) {
				  $("#qifUploadLoading").hide();
					if(data.error == true) {
						$("#qifUploadError").show();
						$("#qifUploadErrorText").text(data.msg);
						$("#jqUploader").show();
					 }
					else {
					  $("#fileToUpload").val('');
					  $("#jqUploader").show();
            $("#qifUploadResultCount").show();
            $("#qifUploadResultCount").text(data.msg);
            if(data.importCount > 0) {
              // show the imported records
						  $('#importDetails').load('index.php', {'ajax':1, 'action': 'listImportTransactions', 'id': data.importId, 'listOnly': 'true'},function(){
                $('#importDetails').show();
                enableWizardStep(3);
                });
              }
            }
          },
				error: function (data, status, e) {
				  alert(data.error+"\n"+status+"\n"+e);
					$("#qifUploadError").show();
					$("#qifUploadErrorText").text(e);
				}
			}
		)
  return false;
	}

// logs out the user after inactivity
function logout() {
  $('#main').load('index.php', {'ajax':1, 'action': 'login'},function(){
    clearTimeout(sessionTime);
    });
  }

// reset the logout feature
function resetLogout() {
  // remove the previous timeout
  clearTimeout(sessionTime);
  // reset it so it starts from now
  sessionTime = setTimeout("logout()", 910000); // 15mns+10secs
  }

// show a status bar with a custom message for a definite time
function showStatus(message,timeout,add) {        
  if (typeof _statusbar == "undefined") {
    // ** Create a new statusbar instance as a global object
    _statusbar = $("<div id='_statusbar' class='statusbar'></div>").appendTo(document.body).show();
    }

  if (add) _statusbar.prepend( "<div style='margin-bottom: 2px;' >" + message + "</div>")[0].focus();
  else _statusbar.text(message)
  
  _statusbar.show();        
  if (timeout) {
    _statusbar.addClass("statusbarhighlight");
    //setTimeout( function() { _statusbar.removeClass("statusbarhighlight"); },timeout);
    setTimeout( function() { _statusbar.hide(); },timeout);
    }
  }

// main function to manage the interface
$(document).ready(function(){  
  // hide the loading div
  $('#loading').hide();

  // table Row highlight on mouse over
  $(".hoverHighlight").live('mouseover', function(event){
    $(this).addClass('highlightedRow');
    });
    
  $(".hoverHighlight").live('mouseout', function(event){
    $(this).removeClass('highlightedRow');
    });
  
  // cloud mouse over on cloud
  $("a[cloud]").live('mouseover', function(event){
    //$("#cloud-div-"+$(this).attr('cloud')).show();
    $("#cloud-"+$(this).attr('cloud')).addClass('highlightedRow');
    });
  
  $("a[cloud]").live('mouseout', function(event){
    //$("#cloud-div-"+$(this).attr('cloud')).hide();
    $("#cloud-"+$(this).attr('cloud')).removeClass('highlightedRow');
    });

  // edit category link (submit the form)
  $("a[editCategory]").live('click', function(event){
    event.preventDefault();
    resetLogout();
    // get the data
    var action = 'editCategoriesSubmit';
    var id = $(this).attr('id');
    var categoryName = $('#'+id+'_name').val();
    var categoryColor = $('#'+id+'_color').val();
    var categoryMaxAmountPerMonth = $('#'+id+'_MaxAmountPerMonth').val();
    var postData = 'ajax=1&action='+action+'_id='+id+'_name='+categoryName+'_color='+categoryColor+'_maxAmountPerMonth='+categoryMaxAmountPerMonth;
    // reset to the loading gif and show the loading div
    $('#categoryLoading-'+id).attr({src: "style/icons/icon_loading.gif"});
    $('#categoryLoading-'+id).show();
    // send the request
    $.ajax({
      type: "POST",
      timeout: 15000,
      url: "index.php",
      data: postData,
      timeout: 15000,
      dataType: 'json',
      cache: false,
      success: function(data, status){
        if(data.error == true) $('#categoryLoading-'+id).attr({src: "style/icons/cancel.png"});
        else {
          $('#categoryLoading-'+id).attr({src: "style/icons/accept.png"});
          // update all IDs if new insert
          if(id<0) {
            $('#'+id+'_name').attr('id', data.id+'_name');
            $('#'+id+'_color').attr('id', data.id+'_color');
            $('#'+id+'_MaxAmountPerMonth').attr('id', data.id+'_MaxAmountPerMonth');
            $('#categoryLoading'+id).attr('id', 'categoryLoading'+data.id);
            $('#'+id).attr('id', data.id);
            }
          enableWizardStep(2); 
          }
        showStatus(data.msg, 3000);
        }
      });
    });

  // edit keyword link (submit the form)
  $("a[editKeyword]").live('click', function(event){
    event.preventDefault();
    resetLogout();
    // get the data
    var action = 'editKeywordsSubmit';
    var id = $(this).attr('id');
    var keyword = $('#'+id+'_keyword').val();
    var category = $('#'+id+'_category').val();
    var postData = 'ajax=1&action='+action+'_id='+id+'_keyword='+keyword+'_category='+category;
    // show the loading div
     // reset to the loading gif and show the loading div
    $('#keywordLoading-'+id).attr({src: "style/icons/icon_loading.gif"});
    $('#keywordLoading-'+id).show();
    // send the request
    $.ajax({
      type: "POST",
      timeout: 15000,
      url: "index.php",
      data: postData,
      cache: false,
      dataType: 'json',
      success: function(data, status){
        if(data.error == true) $('#keywordLoading-'+id).attr({src: "style/icons/cancel.png"});
        else {
          $('#keywordLoading-'+id).attr({src: "style/icons/accept.png"});
          // update all IDs if new insert
          if(id<0) {
            $('#'+id+'_keyword').attr('id', data.id+'_keyword');
            $('#'+id+'_category').attr('id', data.id+'_category');
            $('#keywordLoading'+id).attr('id', 'keywordLoading'+data.id);
            $('#'+id).attr('id', data.id);
            }
          enableWizardStep(4);
          }
        showStatus(data.msg, 3000);
        }
      });
    });

  // delete imported files
  $("a[deleteImport]").live('click', function(event){
    event.preventDefault();
    resetLogout();
    if(confirm($('#confirmMessage').val())) {
      var id = $(this).attr('id');
      var postData = 'ajax=1&action=deleteImport_id='+id;
      // show the loading div
      $('#loading').show();
      // send the request
      $.ajax({
        type: "POST",
        timeout: 15000,
        url: "index.php",
        data: postData,
        cache: false,
        dataType: 'json',
        success: function(data, status){
          $('#subAction1').load('index.php', {'ajax':1, 'action': 'manageUpload'},function(){ });
          $('#loading').hide();
          showStatus(data.msg, 3000); 
          }
        });
      }
    });

  // delete a transaction
  $("a[deleteTransaction]").live('click', function(event){
    event.preventDefault();
    resetLogout();
    var id = $(this).attr('id');
    var postData = 'ajax=1&action=deleteTransaction_id='+id;
    // show the loading div
    $('#loading').show();
    // send the request
    $.ajax({
      type: "POST",
      timeout: 15000,
      url: "index.php",
      data: postData,
      cache: false,
      dataType: 'json',
      success: function(data, status){
        if(data.removed == true) {
          $('#buttonImg-'+id).attr({src: "style/icons/arrow_undo.png"}); 
          $('#transaction-'+id).addClass('deletedRow');
          }
        if(data.restored == true) {
          $('#buttonImg-'+id).attr({src: "style/icons/bin_empty.png"});
          $('#transaction-'+id).removeClass('deletedRow');
          }
        //showStatus(data.msg, 3000);
        }
      });
    $('#loading').hide();
    });
    
  // list all transactions imported by a specific file import
  $("a[listImportTransactions]").live('click', function(event){
    event.preventDefault();
    resetLogout();
    var id = $(this).attr('id');
    var postData = 'ajax=1&action=listImportTransactions_id='+id;
    
    // show the loading div
    $('#loading').show();
    // send the request
    $('#importDetails').load('index.php', {'ajax':1, 'action': 'listImportTransactions', 'id': id},function(){
      $('#loading').hide();
      $('#importDetails').show();
      });
    });
  
  // register all 'action' links
  $('a[action]').live('click',function(event){
    event.preventDefault();
    resetLogout();
    // show the loading div
    $('#loading').show();
    path = 'index.php';
    // get if a specific div was requested
    toDiv = $(this).attr('toDiv');
    // if no div is requested, then it is the default one
    if(!toDiv) toDiv = 'main';
    // make sure this div is visible
    $('#'+toDiv).show();
    // load the content
    $('#'+toDiv).load(path, {'ajax':1, 'toDiv': toDiv, 'action': $(this).attr('action')},function(){
      $('#loading').hide();
      });
    });
  
  // manual entry
  $("a[addManualTransaction]").live('click', function(event){
    event.preventDefault();
    resetLogout();
    // hide the submit button
    $('#submitSpan').hide();
    // show the loading span
    $('#loadingSpan').show();
    // get all the values
    var trnDate = $('#datepicker').val();
    var trnAmount = $("#trnAmount").val();
    var trnCategory = $("#trnCategory").val();
    var trnComment = $("#trnComment").val();
    var trnMemo = $("#trnMemo").val();
    var trnDebit = $("input[name=trnDebit]:checked:checked").val(); 
    // make sure we hide the result div
    $('#resultDiv').hide();
    $.ajax({
      type: "POST",
      timeout: 15000,
      url: "index.php",
      dataType: 'json',
      data: "ajax=1&action=addTransactionsManualySubmit_trnDate="+trnDate+"_trnAmount="+trnAmount+"_trnCategory="+trnCategory+"_trnComment="+trnComment+"_trnMemo="+trnMemo+"_trnDebit="+trnDebit,
      cache: false,
      success: function(data, status){
        // hide the loading span
        $('#loadingSpan').hide();
        // show the submit button
        $('#submitSpan').show();
        // we show the result bar
        //showStatus(data.msg, 3000);
        
        // if any error, we show it to the user and we do not clean the form
        if(data.error == true) {
          $('#resultDiv').html('<blockquote>'+data.msg+'</blockquote>');
          $('#resultDiv').removeClass('success');
          $('#resultDiv').addClass('error');
          $('#resultDiv').show();
          }
        else {
          // show the result
          $('#resultDiv').html('<blockquote>'+data.msg+'</blockquote>');
          $('#resultDiv').removeClass('error');
          $('#resultDiv').addClass('success');
          $('#resultDiv').show();
          enableWizardStep(3);
          }
        }
      });
    });
  
  // search form submittion
  $("a[searchFormSubmit]").live('click', function(event){
    event.preventDefault();
    resetLogout();
    // show the loading div
    $('#loading').show();
    $.ajax({
      type: "POST",
      timeout: 15000,
      url: "index.php",
      data: "ajax=1&action=search_keyWord="+$("#keys").val(),
      cache: false,
      success: function(html){
        $("#subAction1").empty();
        $("#subAction1").prepend(html);
        $("#subAction1").show();
        $('#loading').hide();
        }
      });
    });
  
  // date form submittion
  $("a[editdateRange]").live('click', function(event){
    event.preventDefault();
    resetLogout();
    // show the loading div
    $('#loading').show();
    $.ajax({
      type: "POST",
      timeout: 15000,
      url: "index.php",
      dataType: 'json',
      data: "ajax=1&action=setDateRange_monthRange="+$(this).attr('id'),
      cache: false,
      success: function(data, status){
        if(data.error == true) $('#dateFormSubmit').attr({src: "style/icons/cancel.png"});
        else {
            $('#main').load('index.php', {'ajax':1, 'action': 'home'},function(){ 
            $('#loading').hide();
            });
          }
        }
      });
    });

  // Transaction edition -- enhanced
  $("a[categorySelectorSave]").live('click', function (event) {
    event.preventDefault();
    resetLogout();
    // submit the change
    var id = $(this).attr('id');
    var category = $('#categorySelector'+id).val();
    var postData = 'ajax=1&action=editTransactionSubmit_id='+id+'_category='+category;
    // reset to the loading gif and show the loading div
    $('#catLoading-'+id).attr({src: "style/icons/icon_loading.gif"});
    $('#catLoading-'+id).show();
    // send the request
    $.ajax({
      type: "POST",
      timeout: 15000,
      url: "index.php",
      data: postData,
      dataType: 'json',
      cache: false,
      success: function(data, status){
        if(data.error == true) $('#catLoading-'+id).attr({src: "style/icons/cancel.png"});
        else $('#catLoading-'+id).attr({src: "style/icons/accept.png"});
        showStatus(data.msg, 3000);
        //setTimeout( function() { $('#catLoading-'+id).hide(); },3000);
        }
      });
    });

  $("a[commentEntrySave]").live('click', function (event) {
    event.preventDefault();
    resetLogout();
    // submit the change
    var id = $(this).attr('id');
    var comment = $('#commentEntry'+id).val();
    var postData = 'ajax=1&action=editTransactionSubmit_id='+id+'_comment='+comment;
    // show the loading div
    $('#commentLoading-'+id).attr({src: "style/icons/icon_loading.gif"});
    $('#commentLoading-'+id).show();
    // send the request
    $.ajax({
      type: "POST",
      timeout: 15000,
      url: "index.php",
      data: postData,
      dataType: 'json',
      cache: false,
      success: function(data, status){
        if(data.error == true) $('#commentLoading-'+id).attr({src: "style/icons/cancel.png"});
        else $('#commentLoading-'+id).attr({src: "style/icons/accept.png"});
        showStatus(data.msg, 3000);
        //setTimeout( function() { $('#commentLoading-'+id).hide(); },3000);
        }
      });
    });
  // end of ready()
  });
  